package com.hou.serviceuser.controller;

import com.google.common.base.Charsets;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.LoadBalancerBuilder;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.reactive.LoadBalancerCommand;
import com.netflix.ribbon.proxy.annotation.Http;
import org.junit.Test;

import javax.net.ssl.HttpsURLConnection;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 测试Rabbion原生API
 */
public class TestAPI {

    public static void main(String[] args) {
        List<Server> serverList = new ArrayList();
        serverList.add(new Server("localhost",8081));
        serverList.add(new Server("localhost",8082));
        //构建负载均衡实例
        ILoadBalancer iLoadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(serverList);
        for (int i = 0; i <5; i++) {
            Object result = LoadBalancerCommand.builder().
                    withLoadBalancer(iLoadBalancer).build().
                    submit(x -> {
                        try {
                            //直接使用接口最底层调用方式
                            URL url = new URL("http://" + x.getHost() + ":" + x.getPort());
                            System.out.println("调用地址:http://" + x.getHost() + ":" + x.getPort());
                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            conn.setRequestMethod("GET");
                            conn.connect();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }).toBlocking().first();
            System.out.println("服务调用结果:"+result);

        }
    }

    @Test
    public void testBoolum(){
        int total=1000000;
        // 创建过滤器,错误率默认是0.03,值越小存储空间会越大
        // 错误数量约等于 total*(错误率/100)
        BloomFilter<String> bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), total,0.0003);
        //初始化1000000条数据到bloom过滤器中
        for (int i = 0; i < total; i++) {
            bloomFilter.put(""+i);
        }
        //判断值是否在过过滤器中
        int count=0;
        for (int i = 0; i < total+10000; i++) {
            if(bloomFilter.mightContain(""+i))count++;
        }
        System.out.println("总匹配数量:"+count); //= total(肯定可以匹配到)+错误数量
    }
}
